import React from 'react'
import { inject, observer } from 'mobx-react'
import { toJS, autorun } from 'mobx'
import { TabPage,RouteLayout} from 'weaver-mobile-page'
import { withRouter,Route} from 'react-router-dom'
import { Tools, List, Modal } from 'weaver-mobile'
import { WrAlertPage } from "../../../public";
import * as TaskMainApis from '../../../api/task/taskMain'
import Baseinfo from './baseinfo/baseinfo'
import Subtask from './subtask/subtask'
import CommentInfo from './commentinfo/commentInfo'
import OperateLog from './operateLog/operateLog'
import UrgeTask from './urgeTask'
import '../../../style/task/taskDetail.less'
import Relateinfo from './relateinfo/relateinfo'

const FormItem = List.FormItem
const getLabel = Tools.getLabel

@inject("taskDetailStore", "taskMainStore", "taskCommonStore")
@withRouter
@observer
class TaskDetail extends React.Component {

    constructor(props) {
        super(props)
        this.state = { ...props, taskid: "", headPopoverVisile: false, transferpage: 0 }
    }

    componentWillMount() {
        const { changeTaskid, changeCommentReplayAutoFocus } = this.props.taskDetailStore
        const taskid = this.props.match.params.id
        changeTaskid(taskid)

        let paramstr = this.props.location.search
        if (paramstr) {
            let paramobj = {}
            let paramarr = paramstr.substring(1).split("&")
            paramarr.forEach((p, i) => {
                const key = p.split("=")[0]
                const val = p.split("=")[1]
                if (key === "page") {
                    this.state.transferpage = parseInt(val)
                } else if (key === "r_focus" && val == "1") {
                    changeCommentReplayAutoFocus(val)
                }
            })
        }

        let disposer = autorun(() => {
            const { taskid } = this.props.taskDetailStore
            if (this.state.taskid != taskid) {
                this.refreshPage(taskid, this.state.transferpage)
                this.setState({
                    taskid,
                    transferpage: 0
                })
            }
        })

        this.setState({
            disposer
        })
    }

    componentDidMount() {

    }

    componentWillUnmount() {
        const { disposer } = this.state
        const { changeCurrpage, changeTaskDetail } = this.props.taskDetailStore
        changeCurrpage(0)
        changeTaskDetail({})
        disposer && disposer()
    }

    refreshPage = (taskid, page) => {
        const { taskCommonStore } = this.props
        const { changeTaskDetail, changeCurrpage, changeErrormsg } = this.props.taskDetailStore

        changeCurrpage(page || 0)

        taskCommonStore.showLoading()
        TaskMainApis.getTaskDetail({
            taskId: taskid
        }).then(res => {
            taskCommonStore.closeLoading()
            if (res && res.status == "1") {
                res.id = taskid
                changeTaskDetail(res)
            } else {
                changeErrormsg((res && res.errormsg) || "Interface Error" )
            }
        })
    }

    onHeadPopoverSelect = (node) => {
        const { taskid, changeTaskDetailField, taskDetail, changeShowHeadPopover, currpage, changeCurrpage,infoArray } = this.props.taskDetailStore
        const { taskCommonStore, taskDetailStore,history} = this.props
        const value = node.props.value
        const text = node.props.children

        this.setState({
            headPopoverVisile: false
        }, () => {
            if (value === "doing" || value === "complete") {
                taskDetailStore.taskChangeStatus({
                    infos: infoArray[value],
                    status: value === "complete" ? "2" : "1",
                    doback: (newstatus) => {
                        changeTaskDetailField("taskstatus", newstatus || value === "complete" ? "2" : "1")
                    }
                })
            } else if (value === "special" || value === "cancelSpecial") {
                taskDetailStore.taskChangeSpecial({
                    special: value === "special" ? "0" : "1"
                })
            } else if (value === "addfb") {
                currpage != 3 && changeCurrpage(3)
            } else if (value === "delete") {
                taskDetailStore.taskChangeStatus({
                    infos: infoArray[value],
                                status: "4",
                                special: "0",
                                canedit: taskDetail.canedit ? "1" : "0",
                    candel: taskDetail.candel ? "1" : "0",
                    doback: () => {
                                        const { taskListBackendDatas, setTaskBackendDatas, initTaskListDatas } = this.props.taskMainStore
                                        let newTaskListBackendDatas = []
                                        taskListBackendDatas.forEach((d, i) => {
                                            if (d.key != taskid) {
                                                newTaskListBackendDatas.push(d)
                                            }
                                        })
                                        setTaskBackendDatas(newTaskListBackendDatas)
                                        initTaskListDatas()
                                        this.props.history.go(-1)
                                }
                            })
            }else if(value === "resend" || value === "confirm" || value === "audit" || value === "sendback"){ //重发 接收
                taskDetailStore.taskChangeStatus({status:node.key,infos:infoArray[value]});
            }else if(value === "refuse"){//拒绝
                let _this = this;
                Modal.prompt(getLabel(516927, '请填写拒绝理由'), '', [
                    {text: getLabel(201, '取消'),style: 'default'},
                    {
                        text: getLabel('826', '确定'),
                      onPress: (value) => {
                        if(value==''){
                            taskCommonStore.remind(getLabel(516927,'请填写拒绝理由'));
                            return;
                        }
                            taskDetailStore.taskChangeStatus({
                                status: 5, infos: getLabel(515084, '确认要拒绝此任务吗？'), refuseval: value,
                                            doback:function(){
                                                _this.props.history.push("/taskHome");
                      }
                            });
                    }
                    }
                ],'text-required')
            }else if(value === "urgetask"){
                history.push("/taskHome/taskDetail/"+taskid+"/urgeTask")
            }
        })
    }

    render() {
        const { headPopoverVisile } = this.state
        const { tabs, currpage, changeCurrpage, headPopoverlay, taskDetail, taskid, commentReplayAutoFocus, errormsg } = this.props.taskDetailStore

        return (
            errormsg ?
                <WrAlertPage show={true} msg={errormsg} icon={"wuquanxian"} />
                :
                <div className="workrelate-mobile-task-detail">
                    <div className="head-tab-wrapper">
                        <TabPage
                            tabs={tabs}
                            tabProps={
                                {
                                    onChange: (tab, index) => {
                                        changeCurrpage(index)
                                        this.props.history.replace(this.props.location.pathname)
                                    },
                                    page: currpage
                                }
                            }
                            popover
                            popoverProps={
                                {
                                    visible: headPopoverVisile,
                                    overlay: headPopoverlay,
                                    onSelect: this.onHeadPopoverSelect,
                                }
                            }
                        />
                    </div>
                    <div className="detail-content-wrapper">
                        {currpage == 0 &&
                            <Baseinfo detail={taskDetail} />
                        }
                        {currpage == 1 &&
                            <Subtask detail={taskDetail} taskid={taskid} />
                        }
                        {currpage == 2 &&
                            <Relateinfo detail={taskDetail} />
                        }
                        {currpage == 3 &&
                            <CommentInfo detail={taskDetail} taskid={taskid} autoFocus={commentReplayAutoFocus} />
                        }
                        {currpage == 4 &&
                            <OperateLog taskid={taskid} />
                        }
                    </div>
                    <Route
                        key="task-urge"
                        path={"/taskHome/taskDetail/"+taskid+"/urgeTask"}
                        breadcrumbName="催办任务"
                        render={() => (
                            <RouteLayout>
                                <UrgeTask key="route-urgeTask"/>
                            </RouteLayout>
                        )}
                    />
                </div>
        )
    }
}

export default TaskDetail
